#!/bin/bash
#
# [QuickBox Installation Script]
#
# GitHub:   https://github.com/QuickBox/QuickBox
# Author:   QuickBox.IO
# URL:      https://plaza.quickbox.io
#
# QuickBox Copyright (C) 2017 QuickBox.io
# Licensed under GNU General Public License v3.0 GPL-3 (in short)
#
#   You may copy, distribute and modify the software as long as you track
#   changes/dates in source files. Any modifications to our software
#   including (via compiler) GPL-licensed code must also be made available
#   under the GPL along with build & install instructions.
#
#################################################################################
#Script Console Colors
black=$(tput setaf 0); red=$(tput setaf 1); green=$(tput setaf 2); yellow=$(tput setaf 3);
blue=$(tput setaf 4); magenta=$(tput setaf 5); cyan=$(tput setaf 6); white=$(tput setaf 7);
on_red=$(tput setab 1); on_green=$(tput setab 2); on_yellow=$(tput setab 3); on_blue=$(tput setab 4);
on_magenta=$(tput setab 5); on_cyan=$(tput setab 6); on_white=$(tput setab 7); bold=$(tput bold);
dim=$(tput dim); underline=$(tput smul); reset_underline=$(tput rmul); standout=$(tput smso);
reset_standout=$(tput rmso); normal=$(tput sgr0); alert=${white}${on_red}; title=${standout};
sub_title=${bold}${yellow}; repo_title=${black}${on_green}; message_title=${white}${on_magenta}
#################################################################################
function _string() { perl -le 'print map {(a..z,A..Z,0..9)[rand 62] } 0..pop' 15 ; }
#################################################################################

function _bashrc() {
  cp ${local_setup}templates/bashrc.template /root/.bashrc
  profile="/root/.profile"
  if [ ! -f $profile ]; then
    cp ${local_setup}templates/profile.template /root/.profile
  fi
}

# intro function (1)
function _intro() {
  DISTRO=$(lsb_release -is)
  RELEASE=$(lsb_release -rs)
  CODENAME=$(lsb_release -cs)
  SETNAME=$(lsb_release -rc)
  echo
  echo
  echo "[${repo_title}QuickBox${normal}] ${title} QuickBox Seedbox Installation ${normal}  "
  echo
  echo "   ${title}              Heads Up!              ${normal} "
  echo "   ${message_title}  QuickBox works with the following  ${normal} "
  echo "   ${message_title}  Ubuntu 15.10 | 16.04       ${normal} "
  echo
  echo
  echo "${green}Checking distribution ...${normal}"
  if [ ! -x  /usr/bin/lsb_release ]; then
    echo "It looks like you are running $DISTRO, which is not supported by QuickBox."
    echo "Exiting..."
    exit 1
  fi
  echo "$(lsb_release -a)"
  echo
  if [[ ! "$DISTRO" =~ ("Ubuntu") ]]; then
    echo "$DISTRO: ${alert} It looks like you are running $DISTRO, which is not supported by QuickBox ${normal} "
    echo 'Exiting...'
    exit 1
  elif [[ ! "$CODENAME" =~ ("xenial"|"wily") ]]; then
    echo "Oh drats! You do not appear to be running a supported $DISTRO release."
    echo "${bold}$SETNAME${normal}"
    echo 'Exiting...'
    exit 1
  fi
}

# check if root function (2)
function _checkroot() {
  if [[ $EUID != 0 ]]; then
    echo 'This script must be run with root privileges.'
    echo 'Exiting...'
    exit 1
  fi
  echo "${green}Congrats! You're running as root. Let's continue${normal} ... "
  echo
}

function _checkkernel() {
  grsec=$(uname -a | grep -i grs)
  if [[ -n $grsec ]]; then
    echo -e "Your server is currently running with kernel version: $(uname -r)"
    echo -e "Kernels with ${bold}grsec${normal} are not supported"
    echo -ne "${bold}${yellow}Would you like QuickBox to install the distribution kernel?${normal} (Default: ${green}${bold}Y${normal}) "; read input
      case $input in
        [yY] | [yY][Ee][Ss] | "" ) kernel=yes; echo "Your distribution's default kernel will be installed. A reboot will be ${bold}required${normal}."  ;;
        [nN] | [nN][Oo] ) echo "Installer will not continue. Exiting ... "; exit 0 ;;
      *) kernel=yes; echo "Your distribution's default kernel will be installed. A reboot will be ${bold}required${normal}."  ;;
      esac
      if [[ $kernel == yes ]]; then
        if [[ $DISTRO == Ubuntu ]]; then
          apt-get install -q -y linux-image-generic >>"${OUTTO}" 2>&1
        elif [[ $DISTRO == Debian ]]; then
          arch=$(uname -m)
          if [[ $arch =~ ("i686"|"i386") ]]; then
            apt-get install -q -y linux-image-686 >>"${OUTTO}" 2>&1
          elif [[ $arch == x86_64 ]]; then
            apt-get install -q -y linux-image-amd64 >>"${OUTTO}" 2>&1
          fi
        fi
        mv /etc/grub.d/06_OVHkernel /etc/grub.d/25_OVHkernel
        update-grub >>"${OUTTO}" 2>&1
      fi
  fi
}

# check if create log function (3)
function _logcheck() {
  echo -ne "${bold}${yellow}Do you wish to write to a log file?${normal} (Default: ${green}${bold}Y${normal}) "; read input
    case $input in
      [yY] | [yY][Ee][Ss] | "" ) OUTTO="/root/quickbox.$PPID.log";echo "${bold}Output is being sent to /root/quickbox.${magenta}$PPID${normal}${bold}.log${normal}" ;;
      [nN] | [nN][Oo] ) OUTTO="/dev/null 2>&1";echo "${cyan}NO output will be logged${normal}" ;;
    *) OUTTO="/root/quickbox.$PPID.log";echo "${bold}Output is being sent to /root/quickbox.${magenta}$PPID${normal}${bold}.log${normal}" ;;
    esac
  if [[ ! -d /root/tmp ]]; then
    sed -i 's/noexec,//g' /etc/fstab
    mount -o remount /tmp >>"${OUTTO}" 2>&1
  fi
}

# setting system hostname function (7)
function _hostname() {
echo -ne "Please enter a hostname for this server (${bold}Hit ${standout}${green}ENTER${normal} to make no changes${normal}): " ; read input
if [[ -z $input ]]; then
        echo "No hostname supplied, no changes made!!"
else
        hostname ${input}
        echo "${input}">/etc/hostname
        echo "127.0.0.1 ${input}">/etc/hosts
        echo "Hostname set to ${input}"
fi
echo
}

################################################################################
#              RESERVED FOR LETS ENCRYPT SSL INSTALL FUNCTION                  #
################################################################################

function _askquota() {
  echo -ne "${bold}${yellow}Do you wish to use user quotas?${normal} (Default: ${green}${bold}Y${normal}) "; read input
    case $input in
      [yY] | [yY][Ee][Ss] | "" ) quota="yes";echo "${bold}Quotas will be installed${normal}" ;;
      [nN] | [nN][Oo] ) quota="no";echo "${cyan}Quotas will not be installed${normal}" ;;
    *) quota="yes";echo "${bold}Quotas will be installed${normal}" ;;
    esac
}

function _ask10g() {
  echo -ne "${bold}${yellow}Is this a 10 gigabit server?${normal} (Default: ${green}${bold}N${normal}) "; read input
    case $input in
      [yY] | [yY][Ee][Ss] )   if [[ -d /install ]]; then cd /; else mkdir /install; fi;touch /install/.10g.lock;echo "${bold}The devs are officially jealous${normal}" ;;
      [nN] | [nN][Oo] | "" ) echo "${cyan}Who can afford that stuff anyway?${normal}" ;;
    *)  echo "${cyan}Who can afford that stuff anyway?${normal}"  ;;
    esac
    echo
}

# primary partition question
function _askpartition() {
  if [[ $quota == yes ]]; then
  echo
  echo "##################################################################################"
  echo "#${bold} By default the QuickBox script will initiate a build using ${green}/${normal} ${bold}as the${normal}"
  echo "#${bold} primary partition for mounting quotas.${normal}"
  echo "#"
  echo "#${bold} Some providers, such as OVH and SYS force ${green}/home${normal} ${bold}as the primary mount ${normal}"
  echo "#${bold} on their server setups. So if you have an OVH or SYS server and have not"
  echo "#${bold} modified your partitions, it is safe to choose option ${yellow}2)${normal} ${bold}below.${normal}"
  echo "#"
  echo "#${bold} If you are not sure:${normal}"
  echo "#${bold} I have listed out your current partitions below. Your mountpoint will be"
  echo "#${bold} listed as ${green}/home${normal} ${bold}or ${green}/${normal}${bold}. ${normal}"
  echo "#"
  echo "#${bold} Typically, the partition with the most space assigned is your default.${normal}"
  echo "##################################################################################"
  echo
  lsblk
  echo
  echo -e "${bold}${yellow}1)${normal} / - ${green}root mount${normal}"
  echo -e "${bold}${yellow}2)${normal} /home - ${green}home mount${normal}"
  echo -ne "${bold}${yellow}What is your mount point for user quotas?${normal} (Default ${green}1${normal}): "; read version
  case $version in
    1 | "") primaryroot=root  ;;
    2) primaryroot=home  ;;
    *) primaryroot=root ;;
  esac
  echo "Using ${green}$primaryroot mount${normal} for quotas"
  echo
fi
}

function _askcontinue() {
  echo
  echo "Press ${standout}${green}ENTER${normal} when you're ready to begin or ${standout}${red}Ctrl+Z${normal} to cancel" ;read input
  echo
}

# This function blocks an insecure port 1900 that may lead to
# DDoS masked attacks. Only remove this function if you absolutely
# need port 1900. In most cases, this is a junk port.
function _ssdpblock() {
  iptables -I INPUT 1 -p udp -m udp --dport 1900 -j DROP
}

# setting locale function (6)
function _locale() {
echo 'LANGUAGE="en_US.UTF-8"' >> /etc/default/locale
echo 'LC_ALL="en_US.UTF-8"' >> /etc/default/locale
echo "en_US.UTF-8 UTF-8" > /etc/locale.gen
  if [[ -e /usr/sbin/locale-gen ]]; then locale-gen >>"${OUTTO}" 2>&1
  else
    apt-get -y update >>"${OUTTO}" 2>&1
    apt-get install locales -y >>"${OUTTO}" 2>&1
    locale-gen >>"${OUTTO}" 2>&1
    export LANG="en_US.UTF-8"
    export LC_ALL="en_US.UTF-8"
    export LANGUAGE="en_US.UTF-8"
  fi
}

function _askservices() {
  DISTRO=$(lsb_release -is)
  RELEASE=$(lsb_release -rs)
  CODENAME=$(lsb_release -cs)
  SETNAME=$(lsb_release -rc)
  echo "You are running $DISTRO $CODENAME"
  echo "This distribution has support for systemd services. "
  echo "Would you like to enable? (recommended) (Default: ${green}${bold}Y${normal})"; read input
    case $input in
      [yY] | [yY][Ee][Ss] | "" ) cron="no";echo "${bold}Using systemd for process management${normal}" ;;
      [nN] | [nN][Oo] ) cron="yes";echo "${cyan}Cron will manage your processes${normal}" ;;
    *) cron="no";echo "${bold}Using systemd for process management${normal}" ;;
    esac
  echo
}

# ask what rtorrent version (8)
function _askdashtheme() {
  echo -e "1) QuickBox - ${green}smoked${normal} :: Dark theme"
  echo -e "2) QuickBox - ${green}defaulted${normal} :: Light theme"
  echo -ne "${bold}${yellow}Pick your QuickBox Dashboard Theme${normal} (Default ${green}1${normal}): "; read version
  case $version in
    1 | "") dash_theme=smoked  ;;
    2) dash_theme=defaulted  ;;
    *) dash_theme=smoked ;;
  esac
  echo "We will be using QuickBox Theme : ${green}$dash_theme${normal}"
  echo
}

# ask what rtorrent version (8)
function _askrtorrent() {
  echo -e "1) rtorrent ${green}0.9.6${normal}"
  echo -e "2) rtorrent ${green}0.9.4${normal}"
  echo -e "3) rtorrent ${green}0.9.3${normal}"
  echo -ne "${bold}${yellow}What version of rtorrent do you want?${normal} (Default ${green}1${normal}): "; read version
  case $version in
    1 | "") RTVERSION=0.9.6;LTORRENT=0.13.6  ;;
    2) RTVERSION=0.9.4;LTORRENT=0.13.4  ;;
    3) RTVERSION=0.9.3;LTORRENT=0.13.3 ;;
    *) RTVERSION=0.9.6;LTORRENT=0.13.6 ;;
  esac
  echo "We will be using rtorrent-${green}$RTVERSION${normal}/libtorrent-${green}$LTORRENT${normal}"
  echo
}

# ask deluge version (if wanted) (8.1)
function _askdeluge() {
  echo -e "1) Deluge ${green}repo${normal} (fastest)"
  echo -e "2) Deluge with ${green}libtorrent 1.0.11 (stable)${normal}"
  echo -e "3) Deluge with ${green}libtorrent 1.1.3 (dev)${normal}"
  echo -e "4) Do not install Deluge"
  echo -ne "${bold}${yellow}What version of Deluge do you want?${normal} (Default ${green}1${normal}): "; read version
  case $version in
    1 | "") DELUGE=REPO  ;;
    2) DELUGE=1.0.11  ;;
    3) DELUGE=1.1.3 ;;
    4) DELUGE=NO ;;
    *) DELUGE=REPO ;;
  esac
  echo "We will be using Deluge with Libtorrent ${DELUGE}"
  echo
}

# install transmission question (8.5)
function _asktr() {
  echo -ne "${bold}${yellow}Would you like to install transmission? ${normal} [${green}y${normal}]es or [n]o: "; read responce
  case $responce in
    [yY] | [yY][Ee][Ss] | "" ) tr=yes ;;
    [nN] | [nN][Oo]) tr=no ;;
    *) tr=no ;;
  esac
  echo
}

# adduser function (9)
function _adduser() {
  theshell="/bin/bash";
  echo "${bold}${yellow}Add a Master Account user to sudoers${normal}";
  echo -n "Username: "; read user
  username=$(echo "$user"|sed 's/.*/\L&/')
  useradd "${username}" -m -G www-data -s "${theshell}"
  echo -n "Password: (hit enter to generate a password) "; read 'password'
  if [[ ! -z "${password}" ]]; then
    echo "setting password to ${password}"
    passwd=${password}
    echo "${username}:${passwd}" | chpasswd >>"${OUTTO}" 2>&1
    (echo -n "${username}:${REALM}:" && echo -n "${username}:${REALM}:${passwd}" | md5sum | awk '{print $1}' ) >> "${HTPASSWD}"
  else
    echo "setting password to ${genpass}"
    passwd=${genpass}
    echo "${username}:${passwd}" | chpasswd >>"${OUTTO}" 2>&1
    (echo -n "${username}:${REALM}:" && echo -n "${username}:${REALM}:${passwd}" | md5sum | awk '{print $1}' ) >> "${HTPASSWD}"
  fi
  printf "${username}:${passwd}" > /root/"$username".info.db
  echo
}

# install ffmpeg question (10)
function _askffmpeg() {
  echo -ne "${bold}${yellow}Would you like to install ffmpeg? (Used for screenshots)${normal} [${green}y${normal}]es or [n]o: "; read responce
  case $responce in
    [yY] | [yY][Ee][Ss] | "" ) ffmpeg=yes ;;
    [nN] | [nN][Oo] ) ffmpeg=no ;;
    *) ffmpeg=yes ;;
  esac
  echo
}

# ask user for pure-ftpd conf (10.5)
function _askvsftpd() {
  local DEFAULTIP=$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1');
  echo -ne "${bold}${yellow}Please, write your public server IP (used for ftp)${normal} (Default: ${green}${bold}$DEFAULTIP${normal}) "; read input
  if [[ -z "$input" ]]; then
    IP=$DEFAULTIP
  else
    IP=$input
  fi
  
  echo
}

# ban public trackers [iptables option] (11)
function _denyhosts() {
  echo -ne "${bold}${yellow}Block Public Trackers?${normal}: [${green}y${normal}]es or [n]o: "; read responce
  case $responce in
    [yY] | [yY][Ee][Ss] | "")

  echo "[ ${red}-  Blocking public trackers  -${normal} ]"
  cp ${local_setup}templates/trackers.template /etc/trackers
  cp ${local_setup}templates/denypublic.template /etc/cron.daily/denypublic
  chmod +x /etc/cron.daily/denypublic
  cat ${local_setup}templates/hostsTrackers.template >> /etc/hosts
    ;;

    [nN] | [nN][Oo] ) echo "[ ${green}+  Allowing public trackers  +${normal} ]"
    ;;
  esac
  echo
}

# install bbr question (x)
function _askbbr() {
  echo -ne "${bold}${yellow}Would you like to install bbr? (Used for Congestion Control)${normal} [${green}y${normal}]es or [n]o: "; read responce
  case $responce in
    [yY] | [yY][Ee][Ss] | "" ) bbr=yes ;;
    [nN] | [nN][Oo]) bbr=no ;;
    *) bbr=yes ;;
  esac
  echo
}

# package and repo addition (silently add php7) _add respo sources_ (12)
function _repos() {
  apt-get install -y software-properties-common >>"${OUTTO}" 2>&1
  apt-get -y install lsb-release sudo >>"${OUTTO}" 2>&1
  if [[ $DISTRO == Ubuntu ]]; then
    LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php -y >>"${OUTTO}" 2>&1;
  fi

  if [[ $DISTRO == Debian ]]; then
    echo "deb http://packages.dotdeb.org $(lsb_release -sc) all" > /etc/apt/sources.list.d/dotdeb-php7-$(lsb_release -sc).list
    echo "deb-src http://packages.dotdeb.org $(lsb_release -sc) all" >> /etc/apt/sources.list.d/dotdeb-php7-$(lsb_release -sc).list
    wget -q https://www.dotdeb.org/dotdeb.gpg
    sudo apt-key add dotdeb.gpg >> /dev/null 2>&1
  fi

}

# package and repo addition (13) _update and upgrade_
function _updates() {
  if [[ $DISTRO == Debian ]]; then
    cp ${local_setup}templates/apt.sources/debian.template /etc/apt/sources.list
    sed -i "s/RELEASE/${CODENAME}/g" /etc/apt/sources.list
    apt-get --yes --force-yes update >>"${OUTTO}" 2>&1
    yes '' | apt-get install --force-yes build-essential debian-archive-keyring \
                             python-software-properties >>"${OUTTO}" 2>&1
    apt-get --yes --force-yes install deb-multimedia-keyring >>"${OUTTO}" 2>&1
  else
    cp ${local_setup}templates/apt.sources/ubuntu.template /etc/apt/sources.list
    sed -i "s/RELEASE/${CODENAME}/g" /etc/apt/sources.list
    apt-get -y update >>"${OUTTO}" 2>&1
    apt-get -y -f install build-essential debian-archive-keyring \
                             python-software-properties >>"${OUTTO}" 2>&1
    #apt-get -y -f --allow-unauthenticated install deb-multimedia-keyring >>"${OUTTO}" 2>&1
  fi

  if [[ $DISTRO == Debian ]]; then
    export DEBIAN_FRONTEND=noninteractive
    yes '' | apt-get update >>"${OUTTO}" 2>&1
    apt-get -y purge samba samba-common >>"${OUTTO}" 2>&1
    yes '' | apt-get upgrade >>"${OUTTO}" 2>&1
  else
    export DEBIAN_FRONTEND=noninteractive
    apt-get -y update >>"${OUTTO}" 2>&1
    apt-get -y purge samba samba-common >>"${OUTTO}" 2>&1
    apt-get -y upgrade >>"${OUTTO}" 2>&1
  fi

  if [[ -e /etc/ssh/sshd_config ]]; then
    echo "Port 4747" /etc/ssh/sshd_config >> /dev/null 2>&1
    sed -i 's/Port 22/Port 4747/g' /etc/ssh/sshd_config
    #sed -i 's/SendEnv LANG LC_*/#SendEnv LANG LC_*/g' /etc/ssh/ssh_config
    #sed -i 's/AcceptEnv LANG LC_*/#AcceptEnv LANG LC_*/g' /etc/ssh/sshd_config
    service ssh restart >>"${OUTTO}" 2>&1
  fi

  # Create the service lock file directory
  if [[ -d /install ]]; then cd /; else mkdir /install; fi
  if [[ -d /root/tmp ]]; then cd && rm -r tmp; fi

}

# package and repo addition (14) _install softwares and packages_
function _depends() {
  if [[ $DISTRO == Debian ]]; then
    yes '' | apt-get install --force-yes fail2ban bc ed sudo screen zip irssi unzip nano bwm-ng htop nethogs speedtest.cli iotop \
                     dos2unix subversion dstat automake make mktorrent libtool libcppunit-dev libssl-dev \
                     pkg-config libxml2-dev libcurl3 libcurl4-openssl-dev libsigc++-2.0-dev \
                     apache2-utils autoconf cron curl libapache2-mod-fastcgi libapache2-mod-geoip \
                     libxslt-dev libncurses5-dev yasm pcregrep apache2 php-net-socket libapache2-mod-php7.0 \
                     php7.0-dev php7.0-geoip libgeoip-dev php7.0 php7.0-fpm php7.0-mbstring php7.0-mysql \
                     php7.0-curl php7.0-memcached memcached php7.0-gd php7.0-json php7.0-mcrypt php7.0-opcache \
                     php7.0-xml python3-lxml python-lxml fontconfig comerr-dev ca-certificates libfontconfig1-dev \
                     libdbd-mysql-perl libdbi-perl libfontconfig1 rar unrar mediainfo ifstat \
                     ttf-mscorefonts-installer checkinstall dtach cfv libarchive-zip-perl \
                     libnet-ssleay-perl ca-certificates-java libxslt1-dev \
                     libxslt1.1 libxml2 libffi-dev python-pip python-dev libhtml-parser-perl libxml-libxml-perl \
                     libjson-perl libjson-xs-perl libxml-libxslt-perl libapache2-mod-scgi \
                     vnstat vnstati openvpn >>"${OUTTO}" 2>&1
  elif [[ $DISTRO == Ubuntu ]]; then
    apt-get -y -f --allow-unauthenticated install build-essential debian-archive-keyring fail2ban bc sudo \
                     screen zip irssi unzip nano bwm-ng htop iotop git \
                     dos2unix subversion dstat automake make mktorrent libtool libcppunit-dev libssl-dev \
                     pkg-config libxml2-dev libcurl3 libcurl4-openssl-dev libsigc++-2.0-dev \
                     apache2-utils autoconf cron curl libapache2-mod-fastcgi libapache2-mod-geoip \
                     libxslt-dev libncurses5-dev yasm pcregrep apache2 php-net-socket \
                     libdbd-mysql-perl libdbi-perl php7.0 php7.0-fpm php7.0-mbstring php7.0-mysql \
                     php7.0-curl php-memcached memcached php7.0-gd php7.0-json php7.0-mcrypt php7.0-opcache \
                     php7.0-xml php7.0-zip fontconfig comerr-dev ca-certificates libfontconfig1-dev \
                     php7.0-geoip libfontconfig1 rar unrar mediainfo ifstat libapache2-mod-php7.0 \
                     python3-lxml python-lxml ttf-mscorefonts-installer checkinstall dtach cfv libarchive-zip-perl \
                     libnet-ssleay-perl openjdk-8-jre-headless openjdk-8-jre openjdk-8-jdk libxslt1-dev \
                     libxslt1.1 libxml2 libffi-dev python-pip python-dev libhtml-parser-perl libxml-libxml-perl \
                     libjson-perl libjson-xs-perl libxml-libxslt-perl libapache2-mod-scgi \
                     vnstat vnstati openvpn >>"${OUTTO}" 2>&1
  fi
}

# build openssl from source to combat recent apt source updates
function _openssl() {
  MAXCPUS=$(echo "$(nproc) / 2"|bc)
  cd /root
  wget -q https://www.openssl.org/source/openssl-1.0.2l.tar.gz
  tar -zxvf openssl-1.0.2l.tar.gz >>"${OUTTO}" 2>&1
  cd openssl-1.0.2l
  ./config -fPIC >>"${OUTTO}" 2>&1;
  make -j${MAXCPUS} >>"${OUTTO}" 2>&1;
  #make install >>"${OUTTO}" 2>&1;
  cd /root
  rm -rf openssl-1.0.2l.tar.gz
  cd
}

function _syscommands() {
  mkdir -p /usr/local/bin/quickbox
  cp -r ${local_packages}/. /usr/local/bin/quickbox
  dos2unix $(find /usr/local/bin/quickbox -type f) >>"${OUTTO}" 2>&1;
  chmod +x $(find /usr/local/bin/quickbox -type f) >>"${OUTTO}" 2>&1;
  cp /usr/local/bin/quickbox/system/reload /usr/bin/reload
}

function _skel() {
  if [[ -d /etc/skel ]]; then rm -r /etc/skel;fi
  mkdir /etc/skel
  cp -r ${local_setup}templates/skel/. /etc/skel
  tar xzf ${local_setup}sources/rarlinux-x64-5.3.0.tar.gz -C ./
  cp ./rar/*rar /usr/bin
  cp ./rar/*rar /usr/sbin
  rm -rf rarlinux*.tar.gz
  rm -rf ./rar
  wget -q http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
  gunzip GeoLiteCity.dat.gz>>"${OUTTO}" 2>&1
  mkdir -p /usr/share/GeoIP>>"${OUTTO}" 2>&1
  rm -rf GeoLiteCity.dat.gz
  mv GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat>>"${OUTTO}" 2>&1
  (echo y;echo o conf prerequisites_policy follow;echo o conf commit)>/dev/null 2>&1|cpan Digest::SHA1 >>"${OUTTO}" 2>&1
  (echo y;echo o conf prerequisites_policy follow;echo o conf commit)>/dev/null 2>&1|cpan Digest::SHA >>"${OUTTO}" 2>&1
  if [[ $DELUGE != NO ]]; then
    mkdir -p /etc/skel/.config/deluge/plugins/
    cd /etc/skel/.config/deluge/plugins/
    wget -q https://github.com/ratanakvlun/deluge-ltconfig/releases/download/v0.2.5.0/ltConfig-0.2.5.0-py2.7.egg
  fi
}

function _qmount() {
  # Setup mount points for Quotas
  if [[ $quota == yes ]]; then
    if [[ $DISTRO == Ubuntu ]]; then
      if [[ ${primaryroot} == "root" ]]; then
        sed -ie '/\/ / s/defaults/usrjquota=aquota.user,jqfmt=vfsv1,defaults/' /etc/fstab
        sed -i 's/errors=remount-ro/usrjquota=aquota.user,jqfmt=vfsv1,errors=remount-ro/g' /etc/fstab
        apt-get install -y linux-image-extra-virtual quota >>"${OUTTO}" 2>&1
        mount -o remount / || mount -o remount /home >>"${OUTTO}" 2>&1
        quotacheck -auMF vfsv1 >>"${OUTTO}" 2>&1
        quotaon -uv / >>"${OUTTO}" 2>&1
        service quota start >>"${OUTTO}" 2>&1
      else
        sed -ie '/\/home/ s/defaults/usrjquota=aquota.user,jqfmt=vfsv1,defaults/' /etc/fstab
        sed -i 's/errors=remount-ro/usrjquota=aquota.user,jqfmt=vfsv1,errors=remount-ro/g' /etc/fstab
        apt-get install -y linux-image-extra-virtual quota >>"${OUTTO}" 2>&1
        mount -o remount /home >>"${OUTTO}" 2>&1
        quotacheck -auMF vfsv1 >>"${OUTTO}" 2>&1
        quotaon -uv /home >>"${OUTTO}" 2>&1
        service quota start >>"${OUTTO}" 2>&1
      fi
    elif [[ $DISTRO == Debian ]]; then
      if [[ ${primaryroot} == "root" ]]; then
        sed -ie '/\/ / s/defaults/usrjquota=aquota.user,jqfmt=vfsv1,defaults/' /etc/fstab
        sed -i 's/errors=remount-ro/usrjquota=aquota.user,jqfmt=vfsv1,errors=remount-ro/g' /etc/fstab
        apt-get install -y quota >>"${OUTTO}" 2>&1
        mount -o remount / || mount -o remount /home >>"${OUTTO}" 2>&1
        quotacheck -auMF vfsv1 >>"${OUTTO}" 2>&1
        quotaon -uv / >>"${OUTTO}" 2>&1
        service quota start >>"${OUTTO}" 2>&1
      else
        sed -ie '/\/home/ s/defaults/usrjquota=aquota.user,jqfmt=vfsv1,defaults/' /etc/fstab
        sed -i 's/errors=remount-ro/usrjquota=aquota.user,jqfmt=vfsv1,errors=remount-ro/g' /etc/fstab
        apt-get install -y quota >>"${OUTTO}" 2>&1
        mount -o remount /home >>"${OUTTO}" 2>&1
        quotacheck -auMF vfsv1 >>"${OUTTO}" 2>&1
        quotaon -uv /home >>"${OUTTO}" 2>&1
        service quota start >>"${OUTTO}" 2>&1
      fi
    fi
    touch /install/.quota.lock
  fi
}

function _lshell() {
# Setup LShell configuration file
  apt-get -y install lshell >> /dev/null 2>&1
  cp ${local_setup}templates/lshell.conf.template /etc/lshell.conf
}

# build function for ffmpeg (17)
function _ffmpeg() {
  if [[ ${ffmpeg} == "yes" ]]; then
    MAXCPUS=$(echo "$(nproc) / 2"|bc)
    if [[ $DISTRO == Ubuntu ]]; then
      apt-get -y install x265 >>"${OUTTO}" 2>&1
    elif [[ $DISTRO == Debian ]]; then
      apt-get -y install -t jessie-backports x265 >>"${OUTTO}" 2>&1
    fi
    mkdir /root/tmp
    cd /root/tmp
    if [[ -d /root/tmp/ffmpeg ]]; then rm -rf ffmpeg;fi
    git clone --depth 1 -b release/3.2 https://github.com/FFmpeg/FFmpeg.git ffmpeg >>"${OUTTO}" 2>&1
    git clone git://github.com/yasm/yasm.git ffmpeg/yasm >>"${OUTTO}" 2>&1
    git clone https://github.com/yixia/x264.git ffmpeg/x264 >>"${OUTTO}" 2>&1
    ############################################################################
    ## x265 needs to be manually compiled - there is no non-interactive option.
    #git clone https://github.com/videolan/x265.git ffmpeg/x265 >>"${OUTTO}" 2>&1
    ############################################################################
    ####---- Github Mirror source ----####
    #git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg >>"${OUTTO}" 2>&1
    ############################################################################
    cd ffmpeg/yasm
    ./autogen.sh >>"${OUTTO}" 2>&1
    ./configure >>"${OUTTO}" 2>&1
    make >>"${OUTTO}" 2>&1
    make install >>"${OUTTO}" 2>&1
    cd ../x264
    ./configure --enable-static --enable-shared >>"${OUTTO}" 2>&1
    make >>"${OUTTO}" 2>&1
    make install >>"${OUTTO}" 2>&1
    ldconfig >>"${OUTTO}" 2>&1
    ############################################################################
    ## x265 needs to be manually compiled - there is no non-interactive option.
    #cd ../x265/build/linux
    #./make-Makefiles.bash >>"${OUTTO}" 2>&1
    #make >>"${OUTTO}" 2>&1
    #make install >>"${OUTTO}" 2>&1
    #ldconfig >>"${OUTTO}" 2>&1
    ############################################################################
    cd /root/tmp/ffmpeg
    export FC_CONFIG_DIR=/etc/fonts
    export FC_CONFIG_FILE=/etc/fonts/fonts.conf
    ./configure --enable-libfreetype --enable-filter=drawtext --enable-fontconfig --disable-asm --enable-libx264 --enable-gpl >>"${OUTTO}" 2>&1
    make -j${MAXCPUS} >>"${OUTTO}" 2>&1
    make install >>"${OUTTO}" 2>&1
    cp /usr/local/bin/ffmpeg /usr/bin >>"${OUTTO}" 2>&1
    cp /usr/local/bin/ffprobe /usr/bin >>"${OUTTO}" 2>&1
    rm -rf /root/tmp/ffmpeg >>"${OUTTO}" 2>&1
  fi
}

# function to enable sudo for www-data function (18)
function _apachesudo() {
  rm /etc/sudoers
  cp ${local_setup}templates/sudoers.template /etc/sudoers
  #if [[ $sudoers == "yes" ]]; then
    awk -v username=${username} '/^root/ && !x {print username    " ALL=(ALL:ALL) NOPASSWD: ALL"; x=1} 1' /etc/sudoers > /tmp/sudoers;mv /tmp/sudoers /etc
    echo -n "${username}" > /etc/apache2/master.txt
  #fi
  cd
}

# xmlrpc-c function (19)
function _xmlrpc() {
  if [[ -d /root/tmp ]]; then rm -r tmp;fi
  mkdir /root/tmp && cd /root/tmp
  if [[ -d /root/tmp/xmlrpc-c ]]; then rm -rf xmlrpc-c;fi
  cp -r ${local_setup}sources/xmlrpc-c_1-33-12/ .
  cd xmlrpc-c_1-33-12
  chmod +x configure
  ./configure --prefix=/usr --disable-cplusplus >>"${OUTTO}" 2>&1
  make >>"${OUTTO}" 2>&1
  chmod +x install-sh
  make install >>"${OUTTO}" 2>&1
}

# libtorent function (20)
# apt rtorrent handles the libtorrent install
# remember this is temporary until patched
function _libtorrent() {
  if [[ -d /root/tmp ]]; then rm -r tmp;fi
  mkdir /root/tmp && cd /root/tmp
  MAXCPUS=$(echo "$(nproc) / 2"|bc)
  rm -rf xmlrpc-c  >>"${OUTTO}" 2>&1
  if [[ -e /root/tmp/libtorrent-${LTORRENT}.tar.gz ]]; then rm -rf libtorrent-${LTORRENT}.tar.gz;fi
  cp ${local_setup}sources/libtorrent-${LTORRENT}.tar.gz .
  tar -xzvf libtorrent-${LTORRENT}.tar.gz >>"${OUTTO}" 2>&1
  cd libtorrent-${LTORRENT}
  ./autogen.sh >>"${OUTTO}" 2>&1
  if [ $LTORRENT = 0.13.4 ]; then
  cp ${local_setup}sources/libtorrent-0.13.4-tar.patch .
  patch -p1 < libtorrent-*-tar.patch >>"${OUTTO}" 2>&1
  ./configure --prefix=/usr OPENSSL_LIBS="-L/root/openssl-1.0.2l -lssl -lcrypto" OPENSSL_CFLAGS="-I/root/openssl-1.0.2l/include" --enable-ipv6 >>"${OUTTO}" 2>&1
  else
  ./configure --prefix=/usr OPENSSL_LIBS="-L/root/openssl-1.0.2l -lssl -lcrypto" OPENSSL_CFLAGS="-I/root/openssl-1.0.2l/include" >>"${OUTTO}" 2>&1
  fi
  make -j${MAXCPUS} >>"${OUTTO}" 2>&1
  make install >>"${OUTTO}" 2>&1
}

# rtorrent function (21)
# commenting until patch comes for comp/build 
# using apt install rtorrent in the meantime
function _rtorrent() {
  if [[ -d /root/tmp ]]; then rm -r tmp;fi
  mkdir /root/tmp && cd /root/tmp
  MAXCPUS=$(echo "$(nproc) / 2"|bc)
  rm -rf libtorrent-${LTORRENT}* >>"${OUTTO}" 2>&1
  if [[ -e /root/tmp/libtorrent-${LTORRENT}.tar.gz ]]; then rm -rf libtorrent-${LTORRENT}.tar.gz;fi
  cp ${local_setup}sources/rtorrent-${RTVERSION}.tar.gz .
  tar -xzvf rtorrent-${RTVERSION}.tar.gz >>"${OUTTO}" 2>&1
  cd rtorrent-${RTVERSION}
  ./autogen.sh >>"${OUTTO}" 2>&1
  ./configure --prefix=/usr --with-xmlrpc-c >>"${OUTTO}" 2>&1
  make -j${MAXCPUS} >>"${OUTTO}" 2>&1
  make install >>"${OUTTO}" 2>&1
  cd /root/tmp
  ldconfig >>"${OUTTO}" 2>&1
  rm -rf /root/tmp/rtorrent-${RTVERSION}* >>"${OUTTO}" 2>&1
  touch /install/.rtorrent.lock
}
function _rtorrent_fallback() {
  apt-get install -y rtorrent >>"${OUTTO}" 2>&1
  touch /install/.rtorrent.lock
}

# deluge function (xx)
function _deluge() {
  if [[ $DELUGE == REPO ]]; then
    apt-get -q -y update >>"${OUTTO}" 2>&1
    apt-get -q -y install deluged deluge-web >>"${OUTTO}" 2>&1
    systemctl stop deluged
    update-rc.d deluged remove
    rm /etc/init.d/deluged
  elif [[ $DELUGE == 1.0.11 ]] || [[ $DELUGE == 1.1.3 ]]; then
    if [[ $DELUGE == 1.0.11 ]]; then
      LTRC=RC_1_0
    elif [[ $DELUGE == 1.1.3 ]]; then
      LTRC=RC_1_1
    fi
  apt-get -qy update >/dev/null 2>&1
  LIST='build-essential checkinstall libboost-system-dev libboost-python-dev libssl-dev libgeoip-dev libboost-chrono-dev libboost-random-dev
  python python-twisted python-openssl python-setuptools intltool python-xdg python-chardet geoip-database python-notify python-pygame
  python-glade2 librsvg2-common xdg-utils python-mako'
  for depend in $LIST; do
    apt-get -qq -y install $depend >>"${OUTTO}" 2>&1
  done
  git clone -b ${LTRC} https://github.com/arvidn/libtorrent.git >>"${OUTTO}" 2>&1
  git clone -b 1.3-stable git://deluge-torrent.org/deluge.git >>"${OUTTO}" 2>&1
  cd libtorrent
  ./autotool.sh >>"${OUTTO}" 2>&1
  ./configure --enable-python-binding --with-lib-geoip --with-libiconv >>"${OUTTO}" 2>&1 >>"${OUTTO}" 2>&1
  make -j$(nproc) >>"${OUTTO}" 2>&1
  checkinstall -y --pkgversion=${DELUGE} >>"${OUTTO}" 2>&1
  ldconfig
  cd ..
  cd deluge
  python setup.py build >>"${OUTTO}" 2>&1
  python setup.py install --install-layout=deb >>"${OUTTO}" 2>&1
  python setup.py install_data >>"${OUTTO}" 2>&1
  cd ..
  rm -r {deluge,libtorrent}
fi
  if [[ $DELUGE != NO ]]; then
  n=$RANDOM
  DPORT=$((n%59000+10024))
  DWSALT=$(head /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)
  DWP=$(python ${local_packages}/system/deluge.Userpass.py ${passwd} ${DWSALT})
  DUDID=$(python ${local_packages}/system/deluge.addHost.py)
  # -- Secondary awk command -- #
  #DPORT=$(awk -v min=59000 -v max=69024 'BEGIN{srand(); print int(min+rand()*(max-min+1))}')
  DWPORT=$(shuf -i 10001-11000 -n 1)
  mkdir -p /home/${username}/.config/deluge/plugins
  if [[ ! -f /home/${username}/.config/deluge/plugins/ltConfig-0.2.5.0-py2.7.egg ]]; then
    cd /home/${username}/.config/deluge/plugins/
    wget -q https://github.com/ratanakvlun/deluge-ltconfig/releases/download/v0.2.5.0/ltConfig-0.2.5.0-py2.7.egg
  fi
  chmod 755 /home/${username}/.config
  chmod 755 /home/${username}/.config/deluge
  cp ${local_setup}templates/core.conf.template /home/${username}/.config/deluge/core.conf
  cp ${local_setup}templates/web.conf.template /home/${username}/.config/deluge/web.conf
  cp ${local_setup}templates/hostlist.conf.1.2.template /home/${username}/.config/deluge/hostlist.conf.1.2
  sed -i "s/USERNAME/${username}/g" /home/${username}/.config/deluge/core.conf
  sed -i "s/DPORT/${DPORT}/g" /home/${username}/.config/deluge/core.conf
  sed -i "s/XX/${ip}/g" /home/${username}/.config/deluge/core.conf
  sed -i "s/DWPORT/${DWPORT}/g" /home/${username}/.config/deluge/web.conf
  sed -i "s/DWSALT/${DWSALT}/g" /home/${username}/.config/deluge/web.conf
  sed -i "s/DWP/${DWP}/g" /home/${username}/.config/deluge/web.conf
  sed -i "s/DUDID/${DUDID}/g" /home/${username}/.config/deluge/hostlist.conf.1.2
  sed -i "s/DPORT/${DPORT}/g" /home/${username}/.config/deluge/hostlist.conf.1.2
  sed -i "s/USERNAME/${username}/g" /home/${username}/.config/deluge/hostlist.conf.1.2
  sed -i "s/PASSWD/${passwd}/g" /home/${username}/.config/deluge/hostlist.conf.1.2
  echo "${username}:${passwd}:10" > /home/${username}/.config/deluge/auth
  chmod 600 /home/${username}/.config/deluge/auth
  chown -R ${username}.${username} /home/${username}/.config/
  mkdir /home/${username}/dwatch
  chown ${username}: /home/${username}/dwatch
  mkdir -p /home/${username}/torrents/deluge
  chown ${username}: /home/${username}/torrents/deluge
  touch /install/.deluge.lock
fi
}

function _insTr() {
  apt-get -q -y update >>"${OUTTO}" 2>&1
  apt-get -q -y install transmission-daemon >>"${OUTTO}" 2>&1
  service transmission-daemon stop >>"${OUTTO}" 2>&1
  mkdir -p /home/${username}/torrents/transmission
  chmod g+w /home/${username}/torrents/transmission >/dev/null 2>&1
  #chgrp -R debian-transmission /home/${username}/torrents/transmission
  chown -R ${username}:debian-transmission /home/${username}/torrents/transmission >/dev/null 2>&1
  sed -i "s/\/var\/lib\/transmission-daemon\/downloads/\/home\/${username}\/torrents\/transmission/g" /etc/transmission-daemon/settings.json
  sed -i "s/\/var\/lib\/transmission-daemon\/Downloads/\/home\/${username}\/torrents\/transmission\/incomplete/g" /etc/transmission-daemon/settings.json
  sed -i "s/\"{.*/\"${passwd}\", /g" /etc/transmission-daemon/settings.json
  sed -i "s/\"transmission\",/\"${username}\",/g" /etc/transmission-daemon/settings.json
  sed -i "s/127.0.0.1/\*.\*.\*.\*/g" /etc/transmission-daemon/settings.json
  service transmission-daemon start >>"${OUTTO}" 2>&1
}

function _insTrWeb() {
  rootFolder=""
  webFolder=""
  orgindex="index.original.html"
  index="index.html"
  tmpFolder="/tmp/tr-web-control"
  packname="transmission-control-full.tar.gz"
  host="https://github.com/ronggang/transmission-web-control/raw/master/release/"
  downloadurl="$host$packname"
  if [ ! -d "$tmpFolder" ]; then
	mkdir -p "$tmpFolder"
  fi
  # 找出web ui 目录
  folderIsExist=0
  echo "Searching Transmission Web Folder..." >>"${OUTTO}" 2>&1
  rootFolder="/usr/share/transmission"
  echo "Looking for folder: $rootFolder/web" >>"${OUTTO}" 2>&1
  if [ -d "$rootFolder/web" ]; then
	    webFolder="$rootFolder/web"
	    folderIsExist=1
      echo "Folder found. Using it." >>"${OUTTO}" 2>&1
  else
      echo "Folder not found. Will search the entire /. This will take a while..." >>"${OUTTO}" 2>&1
      rootFolder=`find / -name 'web' -type d 2>/dev/null| grep 'transmission/web' | sed 's/\/web$//g'`
      if [ -d "$rootFolder/web" ]; then
	            webFolder="$rootFolder/web"
	            folderIsExist=1
      fi
  fi

# 如果目录存在，则进行下载和更新动作
  if [ $folderIsExist = 1 ]; then
        cd "$tmpFolder"
      	echo "Downloading Transmission Web Control..." >>"${OUTTO}" 2>&1
      	wget -q "$downloadurl"
      	echo "Installing..." >>"${OUTTO}" 2>&1
      	tar -xzvf "$packname" -C "$tmpFolder" >>"${OUTTO}" 2>&1
      	rm "$packname"
      	# 如果之前没有安装过，则先将原系统的文件改为
      	if [ ! -f "$webFolder/$orgindex" -a -f "$webFolder/$index" ]; then
      		      mv "$webFolder/$index" "$webFolder/$orgindex"
      	fi
      	# 复制文件到
      	cp -r web "$rootFolder"
        find "$rootFolder" -type d -exec chmod o+rx {} \;
        find "$rootFolder" -type f -exec chmod o+r {} \;
      	echo "Done." >>"${OUTTO}" 2>&1
  else
      	#echo "##############################################"
      	#echo "#"
      	echo "# ERROR : Transmisson WEB UI Folder is missing." >>"${OUTTO}" 2>&1
      	#echo "#"
      	#echo "##############################################"
  fi
  rm -rf "$tmpFolder"
  touch /install/.transmission.lock
  #cd ${local_dashboard}/custom
  #patch -p1 < ${local_setup}templates/tr-php.patch >>"${OUTTO}" 2>&1
}

# scgi enable function (22-nixed)
# function _scgi() { ln -s /etc/apache2/mods-available/scgi.load /etc/apache2/mods-enabled/scgi.load >>"${OUTTO}" 2>&1 ; }

# mktorrent function (xx)
function _mktorrent() {
  if [[ -d /root/tmp ]]; then rm -r tmp;fi
  mkdir /root/tmp && cd /root/tmp
  mktorrent_version=1.1
  wget --quiet https://github.com/Rudde/mktorrent/archive/v$mktorrent_version.zip -O mktorrent.zip  >>"${OUTTO}" 2>&1
  unzip -o mktorrent.zip  >>"${OUTTO}" 2>&1
  cd mktorrent-1.1
  make >>"${OUTTO}" 2>&1
  make install >>"${OUTTO}" 2>&1
  cd ..
  rm -rf mktorrent-1.1 && rm -f mktorrent.zip
}

# function to install rutorrent (22)
function _rutorrent() {
  cd /srv
  if [[ -d /srv/rutorrent ]]; then rm -rf rutorrent;fi
  mkdir rutorrent
  cp -r ${local_rutorrent}/. rutorrent
}

function _rutorrent-plugins() {
  cd /srv/rutorrent
  if [[ -d /srv/rutorrent/plugins ]]; then rm -rf plugins;fi
  mkdir plugins
  cp -R ${local_rplugins}/. plugins
}

# function to install dashboard (23)
function _dashboard() {
  cd && mkdir -p /srv/rutorrent/home
  cp -r ${local_dashboard}. /srv/rutorrent/home
  touch /srv/rutorrent/home/db/output.log
  touch /srv/rutorrent/home/db/.${dash_theme}.lock
}

# function to install _h5ai file indexer (24x)
function _fileindexer() {
  cd /srv/rutorrent/home
  wget --quiet https://release.larsjung.de/h5ai/h5ai-0.29.0.zip >>"${OUTTO}" 2>&1
  unzip h5ai-0.29.0.zip >>"${OUTTO}" 2>&1
  rm –rf h5ai-0.29.0.zip >>"${OUTTO}" 2>&1
  chmod 775 -R _h5ai/private/cache && chmod 775 -R _h5ai/public/cache
  apt -y install imagemagick >>"${OUTTO}" 2>&1
  echo "#DirectoryIndex index.html index.php /_h5ai/public/index.php" >> /etc/apache2/apache2.conf
  ln -s /home/${username}/torrents/rtorrent/ ${username}.rtorrent.downloads
  ln -s /home/${username}/torrents/deluge/ ${username}.deluge.downloads
  if [[ ${tr} == "yes" ]]; then
	ln -s /home/${username}/torrents/transmission/ ${username}.transmission.downloads
  fi
}

# function to configure apache (24)
function _apacheconf() {
  cp ${local_setup}templates/aliases-seedbox.conf.template /etc/apache2/sites-enabled/aliases-seedbox.conf
  sed -i "s/USERNAME/${username}/g" /etc/apache2/sites-enabled/aliases-seedbox.conf
  a2enmod auth_digest >>"${OUTTO}" 2>&1
  a2enmod ssl >>"${OUTTO}" 2>&1
  a2enmod scgi >>"${OUTTO}" 2>&1
  a2enmod rewrite >>"${OUTTO}" 2>&1
  mv /etc/apache2/sites-enabled/000-default.conf /etc/apache2/ >>"${OUTTO}" 2>&1
  cp ${local_setup}templates/default-ssl.conf.template /etc/apache2/sites-enabled/default-ssl.conf
  sed -i "s/USERNAME/${username}/g" /etc/apache2/sites-enabled/default-ssl.conf
  sed -i "s/\"REALM\"/\"${REALM}\"/g" /etc/apache2/sites-enabled/default-ssl.conf
  sed -i "s/HTPASSWD/\/etc\/htpasswd/g" /etc/apache2/sites-enabled/default-ssl.conf
  sed -i "s/PORT/${PORT}/g" /etc/apache2/sites-enabled/default-ssl.conf
  sed -i "s/ServerTokens OS/ServerTokens Prod/g" /etc/apache2/conf-enabled/security.conf
  sed -i "s/ServerSignature On/ServerSignature Off/g" /etc/apache2/conf-enabled/security.conf
  cp ${local_setup}templates/fileshare.conf.template /etc/apache2/sites-enabled/fileshare.conf
    sed -i.bak -e "s/post_max_size = 8M/post_max_size = 64M/" \
               -e "s/upload_max_filesize = 2M/upload_max_filesize = 92M/" \
               -e "s/expose_php = On/expose_php = Off/" \
               -e "s/128M/768M/" \
               -e "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" \
               -e "s/;opcache.enable=0/opcache.enable=1/" \
               -e "s/;opcache.memory_consumption=64/opcache.memory_consumption=128/" \
               -e "s/;opcache.max_accelerated_files=2000/opcache.max_accelerated_files=4000/" \
               -e "s/;opcache.revalidate_freq=2/opcache.revalidate_freq=240/" /etc/php/7.0/fpm/php.ini
    sed -i.bak -e "s/post_max_size = 8M/post_max_size = 64M/" \
               -e "s/upload_max_filesize = 2M/upload_max_filesize = 92M/" \
               -e "s/expose_php = On/expose_php = Off/" \
               -e "s/memory_limit = 128M/memory_limit = 768M/" \
               -e "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" \
               -e "s/;opcache.enable=0/opcache.enable=1/" \
               -e "s/;opcache.memory_consumption=64/opcache.memory_consumption=128/" \
               -e "s/;opcache.max_accelerated_files=2000/opcache.max_accelerated_files=4000/" \
               -e "s/;opcache.revalidate_freq=2/opcache.revalidate_freq=240/" /etc/php/7.0/apache2/php.ini

    # ensure opcache module is activated
    phpenmod -v 7.0 opcache >>"${OUTTO}" 2>&1

    # these modules are purely experimental
    #a2enmod proxy_fcgi >>"${OUTTO}" 2>&1
    #a2dismod mpm_prefork >>"${OUTTO}" 2>&1
    #a2enmod mpm_worker >>"${OUTTO}" 2>&1

    # ensure fastcgi module is activated
    a2enmod actions >>"${OUTTO}" 2>&1
    a2enmod headers >>"${OUTTO}" 2>&1
    a2enmod fastcgi >>"${OUTTO}" 2>&1
    a2enmod proxy_fcgi setenvif >>"${OUTTO}" 2>&1
    a2enconf php7.0-fpm >>"${OUTTO}" 2>&1


    #sed -i 's/memory_limit = 128M/memory_limit = 768M/g' /etc/php/7.0/apache2/php.ini
}

# function to fix cert (24x)
# add by EFS
function _fix_cert() {
  if [ ! -f /etc/ssl/certs/ssl-cert-snakeoila.pem ]
  then 
    openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout /etc/ssl/private/ssl-cert-snakeoil.key -out /etc/ssl/certs/ssl-cert-snakeoil.pem -subj "/C=CN/ST=BJ/L=PRC/O=IT/CN=www.example.com" >>"${OUTTO}" 2>&1
  fi
}

# function to configure first user config (25)
function _rconf() {
  cp ${local_setup}templates/rtorrent.rc.template /home/${username}/.rtorrent.rc
  mkdir -p /home/${username}/torrents/rtorrent
  chown -R ${username}: /home/${username}/torrents
  sed -i "s/USERNAME/${username}/g" /home/${username}/.rtorrent.rc
  sed -i "s/XXX/${PORT}/g" /home/${username}/.rtorrent.rc
  sed -i "s/YYY/${PORTEND}/g" /home/${username}/.rtorrent.rc
  if [[ -f /install/.10g.lock ]]; then
    sed -i "s/hrottle.max_peers.normal.set = 100/hrottle.max_peers.normal.set = 300/g" /home/${username}/.rtorrent.rc
    sed -i "s/throttle.max_uploads.global.set = 100/throttle.max_uploads.global.set = 300/g" /home/${username}/.rtorrent.rc
  fi
}

# function to set proper diskspace plugin (26)
function _plugins() {
  cd "${rutorrent}plugins/"
  if [[ ${primaryroot} == "root" ]]; then
    rm -r ${rutorrent}plugins/diskspaceh
  else
    rm -r ${rutorrent}plugins/diskspace
  fi

  cp /srv/rutorrent/home/fileshare/.htaccess /srv/rutorrent/plugins/fileshare/
  cd /srv/rutorrent/home/fileshare/
  rm -rf share.php
  ln -s ../../plugins/fileshare/share.php
  cp ${local_setup}templates/rutorrent/plugins/fileshare/conf.php.template /srv/rutorrent/plugins/fileshare/conf.php

  sed -i 's/homeDirectory/topDirectory/g' /srv/rutorrent/plugins/filemanager/flm.class.php
  sed -i 's/homeDirectory/topDirectory/g' /srv/rutorrent/plugins/filemanager/settings.js.php
  sed -i 's/showhidden: true,/showhidden: false,/g' "${rutorrent}plugins/filemanager/init.js"
  chown -R www-data.www-data "${rutorrent}"
  cd ${rutorrent}plugins/theme/themes/
  git clone https://github.com/QuickBox/club-QuickBox club-QuickBox >>"${OUTTO}" 2>&1
  chown -R www-data:www-data club-QuickBox
  cd ${rutorrent}plugins
  perl -pi -e "s/\$defaultTheme \= \"\"\;/\$defaultTheme \= \"club-QuickBox\"\;/g" ${rutorrent}plugins/theme/conf.php
  rm -rf ${rutorrent}plugins/tracklabels/labels/nlb.png

  # Needed for fileupload
  # wget http://ftp.nl.debian.org/debian/pool/main/p/plowshare/plowshare4_2.1.3-1_all.deb -O plowshare4.deb >>"${OUTTO}" 2>&1
  # wget http://ftp.nl.debian.org/debian/pool/main/p/plowshare/plowshare_2.1.3-1_all.deb -O plowshare.deb >>"${OUTTO}" 2>&1
  apt-get -y install plowshare >>"${OUTTO}" 2>&1
  dpkg -i plowshare*.deb >>"${OUTTO}" 2>&1
  rm -rf plowshare*.deb >>"${OUTTO}" 2>&1
  cd /root
  mkdir -p /root/bin
  git clone https://github.com/mcrapet/plowshare.git ~/.plowshare-source >>"${OUTTO}" 2>&1
  cd ~/.plowshare-source >>"${OUTTO}" 2>&1
  make install PREFIX=$HOME >>"${OUTTO}" 2>&1
  cd && rm -rf .plowshare-source >>"${OUTTO}" 2>&1
  apt-get -f install >>"${OUTTO}" 2>&1

  mkdir -p /srv/rutorrent/conf/users/"${username}"/plugins/fileupload/
  chmod 775 /srv/rutorrent/plugins/fileupload/scripts/upload
  cp /srv/rutorrent/plugins/fileupload/conf.php /srv/rutorrent/conf/users/"${username}"/plugins/fileupload/conf.php
  chown -R www-data: /srv/rutorrent/conf/users/"${username}"

  # Set proper permissions to filemanager so it may execute commands
  find /srv/rutorrent/plugins/filemanager/scripts -type f -exec chmod 755 {} \;
}

# function autodl to install autodl irssi scripts (27)
function _autodl() {
  mkdir -p "/home/${username}/.irssi/scripts/autorun/" >>"${OUTTO}" 2>&1
  cd "/home/${username}/.irssi/scripts/"
  # Grab the most recent version of AutoDL-trackers
  #curl -sL https://api.github.com/repos/autodl-community/autodl-trackers/releases/latest | grep -Po '(?<="browser_download_url": ")(.*-v[\d.]+.zip)' | xargs wget --quiet -O autodl-trackers.zip
  #cd AutodlIrssi
  #rm -rf trackers
  #unzip /home/${username}/.irssi/scripts/autodl-trackers.zip -d /home/${username}/.irssi/scripts/AutodlIrssi/trackers
  # Grab the most recent version of AutoDL
  curl -sL http://git.io/vlcND | grep -Po '(?<="browser_download_url": ")(.*-v[\d.]+.zip)' | xargs wget --quiet -O autodl-irssi.zip
  unzip -o autodl-irssi.zip >>"${OUTTO}" 2>&1
  #cd "/home/${username}/.irssi/scripts/"
  rm autodl-irssi.zip
  #&& rm autodl-trackers.zip
  cp autodl-irssi.pl autorun/
  mkdir -p "/home/${username}/.autodl" >>"${OUTTO}" 2>&1
  touch "/home/${username}/.autodl/autodl.cfg"
  chown ${username}: /home/${username}/.autodl/autodl.cfg
  touch /install/.autodlirssi.lock

cat >"/home/${username}/.autodl/autodl2.cfg"<<ADC
[options]
gui-server-port = ${AUTODLPORT}
gui-server-password = ${AUTODLPASSWORD}
ADC

  chown -R "${username}.${username}" "/home/${username}/.irssi/"
  chown -R "${username}.${username}" "/home/${username}"
}

# function to make dirs for first user (28)
function _makedirs() {
  #mkdir /home/"${username}"/{torrents,.sessions,watch} >>"${OUTTO}" 2>&1
  cp -r /etc/skel/. /home/"${username}"
  chown -r "${username}".www-data /home/"${username}" >>"${OUTTO}" 2>&1 #/{torrents,.sessions,watch,.rtorrent.rc} >>"${OUTTO}" 2>&1
  usermod -a -G www-data "${username}" >>"${OUTTO}" 2>&1
  usermod -a -G "${username}" www-data >>"${OUTTO}" 2>&1
}

# function to make crontab .statup file (29)
#function _cronfile() {
#  cp ${local_setup}templates/startup.template /home/${username}/.startup
#  chmod 775 /home/${username}/.startup
#  if [[ $DELUGE != NO ]]; then
#  sed -i 's/DELUGEWEB_CLIENT=no/DELUGEWEB_CLIENT=yes/g' /home/${username}/.startup
#  sed -i 's/DELUGED_CLIENT=no/DELUGED_CLIENT=yes/g' /home/${username}/.startup
#fi
#}

# function to configure first user config.php (30)
function _ruconf() {
  mkdir -p ${rutorrent}conf/users/${username}/

  cp ${local_setup}templates/rutorrent.users.config.template ${rutorrent}conf/users/${username}/config.php

  chown -R www-data.www-data "${rutorrent}conf/users/" >>"${OUTTO}" 2>&1
  if [[ ${primaryroot} == "root" ]]; then
    sed -i "/diskuser/c\$diskuser = \"\/\";" /srv/rutorrent/conf/users/${username}/config.php
  else
    sed -i "/diskuser/c\$diskuser = \"\/home\";" /srv/rutorrent/conf/users/${username}/config.php
  fi
  sed -i "/quotaUser/c\$quotaUser = \"${username}\";" /srv/rutorrent/conf/users/${username}/config.php
  sed -i "s/USERNAME/${username}/g" /srv/rutorrent/conf/users/${username}/config.php
  sed -i "s/XXX/${PORT}/g" /srv/rutorrent/conf/users/${username}/config.php
  sed -i "s/YYY/${AUTODLPORT}/g" /srv/rutorrent/conf/users/${username}/config.php
  sed -i "s/ZZZ/\"${AUTODLPASSWORD}\"/g" /srv/rutorrent/conf/users/${username}/config.php
}

# function to install pure-ftpd (31)
function _installftpd() {
  apt-get purge -y vsftpd pure-ftpd >>"${OUTTO}" 2>&1
  apt-get autoremove >>"${OUTTO}" 2>&1
  apt-get install -y vsftpd >>"${OUTTO}" 2>&1
}

# function to configure pure-ftpd (32)
function _ftpdconfig() {
  cp ${local_setup}templates/openssl.cnf.template /root/.openssl.cnf

  openssl req -config /root/.openssl.cnf -x509 -nodes -days 365 -newkey rsa:1024 -keyout /etc/ssl/private/vsftpd.pem -out /etc/ssl/private/vsftpd.pem >/dev/null 2>&1

  cp ${local_setup}templates/vsftpd.conf.template /etc/vsftpd.conf

  # Enabling passive mode
  sed -i 's/^\(pasv_min_port=\).*/\110090/' /etc/vsftpd.conf
  sed -i 's/^\(pasv_max_port=\).*/\110100/' /etc/vsftpd.conf
  echo "pasv_address="$IP >> /etc/vsftpd.conf
  iptables -I INPUT -p tcp --destination-port 10090:10100 -j ACCEPT

  echo "" > /etc/vsftpd.chroot_list
}

# The following function makes necessary changes to Network and TZ settings needed for
# the proper functionality of the QuickBox Dashboard.
function _quickstats() {
  # Dynamically adjust to use the servers active network adapter
  printf "${IFACE}" > /srv/rutorrent/home/db/interface.txt
  printf "${username}" > /srv/rutorrent/home/db/master.txt
  # Use server timezone
  cd /usr/share/zoneinfo
  find * -type f -exec sh -c "diff -q /etc/localtime '{}' > /dev/null && echo {}" \; > ~/tz.txt
  cd ~
  LOCALE=en_GB.UTF-8
  LANG=lang_en
  sed -i "s/LOCALE/${locale}/g" /srv/rutorrent/home/inc/localize.php
  sed -i "s/LANG/${lang}/g" /srv/rutorrent/home/inc/localize.php
  #echo "  date_default_timezone_set('$(cat tz.txt)');" >> /srv/rutorrent/home/widgets/config.php
  #echo "" >> /srv/rutorrent/home/widgets/config.php
  #echo "?>" >> /srv/rutorrent/home/widgets/config.php
  if [[ ${primaryroot} == "home" ]]; then
    cd /srv/rutorrent/home/widgets && rm disk_data.php
    mv disk_datah.php disk_data.php
    chown -R www-data:www-data /srv/rutorrent/home/widgets
  else
    rm /srv/rutorrent/home/widgets/disk_datah.php
  fi
}

function _quickconsole() {
  PUBLICIP=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')

cat >/etc/profile<<EOF
echo " Welcome Back !"
echo "    * Dashboard:  https://${PUBLICIP}"
echo "    * Support:    https://plaza.quickbox.io"
echo "    * Donate:     https://quickbox.io/donate"
echo ""
EOF

  apt-get -y install shellinabox >>"${OUTTO}" 2>&1;

  cp ${local_setup}templates/sysd/shellinabox.template /etc/systemd/system/shellinabox.service
  cp ${local_setup}templates/quickconsole/00_QuickConsole.css.template /etc/shellinabox/options-enabled/00_QuickConsole.css
  cp ${local_setup}templates/web-console.conf.template /etc/apache2/sites-enabled/${username}.console.conf

  sed -i "s/PUBLICIP/${PUBLICIP}/g" /etc/apache2/sites-enabled/${username}.console.conf
  sed -i "s/USER/${username}/g" /etc/apache2/sites-enabled/${username}.console.conf

  chmod +x /etc/shellinabox/options-enabled/00_QuickConsole.css
  chmod 777 /etc/shellinabox/options-enabled/00_QuickConsole.css

  systemctl enable shellinabox.service >/dev/null 2>&1
  systemctl stop shellinabox.service >/dev/null 2>&1
  systemctl daemon-reload >/dev/null 2>&1
  systemctl start shellinabox.service >/dev/null 2>&1

}

# seedbox boot for first user (35)
function _boot() {
  #if [[ $cron == yes ]]; then
  #  touch /install/.cron.lock
  #  command1="*/1 * * * * /home/${username}/.startup >/dev/null 2>&1"
  #  cat <(fgrep -iv "${command1}" <(sh -c 'sudo -u ${username} crontab -l' >/dev/null 2>&1)) <(echo "${command1}") | sudo -u ${username} crontab -
  #elif [[ $cron == no ]]; then
  cp ${local_setup}templates/sysd/rtorrent.template /etc/systemd/system/rtorrent@.service >/dev/null 2>&1
  cp ${local_setup}templates/sysd/autodlirssi.template /etc/systemd/system/irssi@.service >/dev/null 2>&1
  cp ${local_setup}templates/sysd/deluged.template /etc/systemd/system/deluged@.service >/dev/null 2>&1
  cp ${local_setup}templates/sysd/deluge-web.template /etc/systemd/system/deluge-web@.service >/dev/null 2>&1
  systemctl enable {rtorrent,irssi,deluged,deluge-web}@${username} >/dev/null 2>&1
  systemctl start {rtorrent,irssi,deluged,deluge-web}@${username} >/dev/null 2>&1
  #fi

  echo "*/1 * * * * root bash /usr/local/bin/quickbox/system/set_interface" > /etc/cron.d/set_interface
}

# function to set permissions on first user (36)
function _perms() {
  chown -R ${username}.${username} /home/${username}/ >>"${OUTTO}" 2>&1
  sudo -u ${username} chmod 755 /home/${username}/ >>"${OUTTO}" 2>&1
  chmod +x /etc/cron.daily/denypublic >/dev/null 2>&1
  chmod 777 /home/${username}/.sessions >/dev/null 2>&1
  chown -R chown -R www-data:www-data /srv/rutorrent/home >/dev/null 2>&1
  if [[ ${tr} == "yes" ]]; then
	chown -R ${username}:debian-transmission /home/${username}/torrents/transmission >/dev/null 2>&1
	service transmission-daemon reload >>"${OUTTO}" 2>&1
  fi
}

function _insbbr() {
  cd /tmp
  cp ${local_setup}sources/BBR/BBR.sh .
  chmod a+x BBR.sh
  bash BBR.sh -f v4.12.14 >>"${OUTTO}" 2>&1
  cd
}

################################################################################
#   //BEGIN UNUSED FUNCTIONS//
################################################################################
# ask for bash or lshell function ()
# Heads Up: lshell is disabled for the initial user on install as your first user
# should not be limited in shell. Additional created users are automagically
# added to a limited shell environment.
function _askshell() {
  #echo -ne "${yellow}Set user shell to lshell?${normal} (Default: ${red}N${normal}): "; read responce
  #case $responce in
  #  [yY] | [yY][Ee][Ss] ) theshell="/usr/bin/lshell" ;;
  #  [nN] | [nN][Oo] | "" ) theshell="/bin/bash" ;;
  #  *) theshell="yes" ;;
  #esac
  echo -ne "${bold}${yellow}Add user to /etc/sudoers${normal} [${green}y${normal}]es or [n]o: "; read answer
  case $answer in
    [yY] | [yY][Ee][Ss] | "" ) sudoers="yes" ;;
    [nN] | [nN][Oo] ) sudoers="no" ;;
    *) sudoers="yes" ;;
  esac
}

# function to create ssl cert for pure-ftpd ()
function _pureftpcert() {
  /bin/true
}
################################################################################
#   //END UNUSED FUNCTIONS//
################################################################################

# function to show finished data (37)
function _finished() {
  ip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')
  echo
  echo
  echo -e " ${black}${on_green}    [quickbox] Seedbox & GUI Installation Completed    ${normal} "
  echo -e "        ${standout}    INSTALLATION COMPLETED in ${FIN}/min    ${normal}             "
  echo;echo
  echo "  Valid Commands:  "
  echo '  -------------------'
  echo
  echo -e " ${green}createSeedboxUser${normal} - creates a shelled seedbox user"
  echo -e " ${green}deleteSeedboxUser${normal} - deletes a created seedbox user and their directories"
  echo -e " ${green}changeUserpass${normal} - change users SSH/FTP/ruTorrent password"
  echo -e " ${green}setdisk${normal} - set your disk quota for any given user"
  echo -e " ${green}showspace${normal} - shows the amount of space used by all users on the server"
  echo -e " ${green}reload${normal} - restarts your seedbox services, i.e; rtorrent & irssi"
  echo -e " ${green}upgradeBTSync${normal} - upgrades BTSync when new version is available"
  echo -e " ${green}upgradeOmbi${normal} - upgrades Ombi when new version is available"
  echo -e " ${green}upgradePlex${normal} - upgrades Plex when new version is available"
  echo -e " ${green}box install letsencrypt${normal} - installs a valid SSL certificate to be used with "
  echo -e "                           a valid domain name. "
  echo -e " ${green}box${normal} - type 'box -h' for a summary of how to use box!"
  echo;echo;echo
  echo '################################################################################################'
  echo "#   Seedbox can be found at https://${username}:${passwd}@${ip} "
  echo "#   ${cyan}(Also works for FTP:5757/SSH:4747)${normal}"
  echo "#   If you need to restart rtorrent/irssi, you can type 'reload'"
  echo "#   https://${username}:${passwd}@${ip} (Also works for FTP:5757/SSH:4747)" > ${username}.info
  echo "#   Reloading: ${green}sshd${normal}, ${green}apache${normal}, ${green}memcached${normal}, ${green}php7.0${normal}, ${green}vsftpd${normal} and ${green}fail2ban${normal}"
  echo '################################################################################################'
  echo

cat >/root/information.info<<EOF
  Seedbox can be found at https://${username}:${passwd}@${ip} (Also works for FTP:5757/SSH:4747)
  If you need to restart rtorrent/irssi, you can type 'reload'
  https://${username}:${passwd}@${ip} (Also works for FTP:5757/SSH:4747)
EOF
  rm -rf "$0" >>"${OUTTO}" 2>&1
    for i in ssh apache2 php7.0-fpm vsftpd fail2ban quota memcached cron; do
      service $i restart >>"${OUTTO}" 2>&1
      systemctl enable $i >>"${OUTTO}" 2>&1
    done
  rm -rf /root/tmp/
  echo -ne "  Do you wish to reboot (recommended!): (Default ${green}Y${normal})"; read reboot
  case $reboot in
    [yY] | [yY][Ee][Ss] | "") reboot                 ;;
    [nN] | [nN][Oo] ) echo "  ${cyan}Skipping reboot${normal} ... " ;;
  esac
}

clear

spinner() {
    local pid=$1
    local delay=0.25
    local spinstr='|/-\'
    while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
        local temp=${spinstr#?}
        printf " [${bold}${yellow}%c${normal}]  " "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        printf "\b\b\b\b\b\b"
    done
    printf "    \b\b\b\b"
    echo -ne "${OK}"
}

local_setup=/etc/QuickBox/setup/
local_packages=/etc/QuickBox/packages/
local_rutorrent=/etc/QuickBox/rutorrent/
local_rplugins=/etc/QuickBox/rtplugins/
local_themes=/etc/QuickBox/themes/
local_dashboard=/etc/QuickBox/dashboard/

IFACE=$(ip link show|grep -i broadcast|grep -m1 UP|cut -d: -f 2|cut -d@ -f 1|sed -e 's/ //g');
HOSTNAME1=$(hostname -s);
PORT=$(shuf -i 2000-61000 -n 1)
PORTEND=$((${PORT} + 1500))
while [[ "$(netstat -ln | grep ':'"$PORT"'' | grep -c 'LISTEN')" -eq "1" ]]; do PORT="$(shuf -i 2000-61000 -n 1)"; done
RPORT=$(shuf -i 2000-61000 -n 1)
while [[ "$(netstat -ln | grep ':'"$RPORT"'' | grep -c 'LISTEN')" -eq "1" ]]; do RPORT="$(shuf -i 2000-61000 -n 1)"; done
S=$(date +%s)
OK=$(echo -e "[ ${bold}${green}DONE${normal} ]")
genpass=$(_string)
HTPASSWD="/etc/htpasswd"
rutorrent="/srv/rutorrent/"
REALM="rutorrent"
AUTODLPASSWORD=$(_string)
AUTODLPORT=$(shuf -i 2000-61000 -n 1)
ip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')
BTSYNCIP=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')
export DEBIAN_FRONTEND=noninteractive
cd

# QuickBox STRUCTURE
_bashrc
_intro
_checkroot
_logcheck
_checkkernel
_hostname
_askquota
_askcontinue
_ssdpblock
_locale
clear

#_askservices
_askpartition
_ask10g
_askrtorrent
_askdeluge
_asktr
_askdashtheme
_adduser
_askffmpeg
_askvsftpd
_denyhosts
_askbbr
clear

echo
echo ""
echo "${bold}${magenta}QuickBox will now install, this may take between${normal}"
echo "${bold}${magenta}10 and 45 minutes depending on your systems specs${normal}"
echo ""
echo -n "Pulling QuickBox Ecosystem ... ";_repos & spinner $!;echo
echo -n "Updating system ... ";_updates & spinner $!;echo
echo -n "Installing all needed dependencies ... ";_depends & spinner $!;echo
_openssl
echo -n "Setting up system executables ... ";_syscommands & spinner $!;echo
echo -n "Building required user directories ... ";_skel & spinner $!;echo
if [[ ${quota} == "yes" ]]; then
echo -n "Setting up quotas for ${green}/($primaryroot)${normal} mount ... ";_qmount & spinner $!;echo
fi
echo -n "Setting up Limited Shell environment ... ";_lshell & spinner $!;echo
if [[ ${ffmpeg} == "yes" ]]; then
    echo -n "Building ffmpeg from source for screenshots ... ";_ffmpeg & spinner $!;echo
fi
_apachesudo
echo -n "Installing xmlrpc-c-${green}1.33.12${normal} ... ";_xmlrpc & spinner $!;echo
echo -n "Installing libtorrent-${green}$LTORRENT${normal} ... ";_libtorrent & spinner $!;echo
echo -n "Installing rtorrent-${green}$RTVERSION${normal} ... ";_rtorrent & spinner $!;echo
#echo -n "Installing rtorrent ... ";_rtorrent_fallback & spinner $!;echo
echo -n "Installing rutorrent into /srv ... ";_rutorrent & spinner $!;echo
echo -n "Installing rutorrent plugins ... ";_rutorrent-plugins & spinner $!;echo
echo -n "Installing deluge ... ";_deluge & spinner $!;echo
if [[ ${tr} == "yes" ]]; then
	echo -n "Configuring Transmisson ... ";_insTr & spinner $!;echo
	echo -n "Installing Transmisson Web Control ... ";_insTrWeb & spinner $!;echo
fi
echo -n "Installing mktorrent from source ... ";_mktorrent & spinner $!;echo
echo -n "Installing quickbox dashboard ... ";_dashboard & spinner $!;echo
echo -n "Building system file indexer (h5ai) ... ";_fileindexer & spinner $!;echo
echo -n "Setting up seedbox.conf for apache ... ";_apacheconf & spinner $!;echo
echo -n "Fix SSL Cert for apache ... ";_fix_cert & spinner $!;echo
echo -n "Installing .rtorrent.rc for ${username} ... ";_rconf & spinner $!;echo
echo -n "Adjusting fileupload & filemanager plugins ... ";_plugins & spinner $!;echo
echo -n "Installing autodl-irssi ... ";_autodl & spinner $!;echo
echo -n "Making ${username} directory structure ... ";_makedirs & spinner $!;echo
echo -n "Writing ${username} rutorrent config.php file ... ";_ruconf & spinner $!;echo
echo -n "Installing vsftpd ... ";_installftpd & spinner $!;echo
echo -n "Setting up vsftpd ... ";_ftpdconfig & spinner $!;echo
_quickstats;
_quickconsole;
echo -n "Setting irssi/rtorrent to start on boot ... ";_boot & spinner $!;echo;
echo -n "Setting permissions on ${username} ... ";_perms & spinner $!;echo;
if [[ ${bbr} == "yes" ]]; then
    echo -n "install BBR ... ";_insbbr & spinner $!;echo
fi
cd
E=$(date +%s)
DIFF=$(echo "$E" - "$S"|bc)
FIN=$(echo "$DIFF" / 60|bc)
clear
_finished
